//
//  SNSTableViewCell.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-28.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "SNSPostViewCell.h"
#import "NetworkAccessManager.h"
#import "UIImageView+AFNetworking.h"
#import "SNSCommentViewController.h"
#import "UIAlertView+Kirinrin.h"
#import "SNSMarkLabelView.h"
#import "UtilHelper.h"

#import <CoreText/CoreText.h>


@interface SNSPostViewCell()

@property (weak, nonatomic) IBOutlet UIView *markContainerView;
@property (strong, nonatomic) NSMutableArray *plusOneImageViewList;
@property (weak, nonatomic) IBOutlet UIView *plusOneContentView;

//for plus one
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView0;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView1;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView2;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView3;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView4;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView5;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView6;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView7;
@property (weak, nonatomic) IBOutlet UIImageView *plusOneImageView8;

@end


@implementation SNSPostViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    
    _plusOneImageViewList = [NSMutableArray arrayWithObjects:_plusOneImageView0, _plusOneImageView1, _plusOneImageView2, _plusOneImageView3, _plusOneImageView4, _plusOneImageView5, _plusOneImageView6, _plusOneImageView7, _plusOneImageView8, nil];
    
    [_plusOneImageViewList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIImageView *imageView = (UIImageView *)obj;
        
//        UIImage *iconImage = [UIImage imageNamed:@"iconChild"];
        UIImage *iconMask =[UIImage imageNamed:@"iconMask"];
        UIImage *iconBorder = [UIImage imageNamed:@"iconBorder"];
//        self.iconView.image = iconImage;
        
        CALayer *borderLayer = [CALayer layer];
        borderLayer.frame = imageView.bounds;
        borderLayer.contents = (id)[iconBorder CGImage];
        
        CALayer *maskLayer = [CALayer layer];
        maskLayer.frame = imageView.bounds;
        maskLayer.contents = (id)[iconMask CGImage];
        
        [[imageView layer]setMask:maskLayer];
        [[imageView layer]addSublayer:borderLayer];
        

    }];
    
//    _commentTextView.contentSize = CGSizeMake(0, 0);
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openPhoto)];
    gesture.numberOfTapsRequired = 1;
    [self.contentPhoto addGestureRecognizer:gesture];
    
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}


-(void)setData:(SNSPostModel *)data{
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    _data = data;
    if (data){
        [self.name setText:data.senderName];
        NSString *sendDateTime = [UtilHelper intervalSinceNow:data.createDate];
        [self.sendDateTime setText:sendDateTime];
        
        if ([appDelegate.userId isEqualToString:self.data.senderId]) {
            self.photo.image = appDelegate.userPhoto;
        }else{
            [self.photo setImageWithURL:data.userPhoto placeholderImage:[UIImage imageNamed:@"image小助手-头像"]];
        }
        
        [self.contentPhoto setImageWithURL:data.photoPre placeholderImage:[UIImage imageNamed:@"image小助手"]];
        
        if ([appDelegate.userId isEqualToString:data.senderId]) {
            self.plusOneButton.enabled = NO;
        }else{
            self.plusOneButton.enabled = YES;
            [self togglePlusOneButton:data.isPlusOne];
        }
        
        if (data.isFavorite) {
            self.favoriteButton.enabled = YES;
            if ([data.isFavorite isEqualToNumber: @(0)]) {
                data.isFavorite = @(0);
                [self.favoriteButton setBackgroundImage: [UIImage imageNamed:@"iconStarGray"]forState:UIControlStateNormal];
            }else{
                data.isFavorite = @(1);
                [self.favoriteButton setBackgroundImage: [UIImage imageNamed:@"iconStarBlue"] forState:UIControlStateNormal];
            }

        }else{
            self.favoriteButton.enabled = NO;
        }
        
        if(data.content){
            [self.content setText: data.content];
        }
        
        if(data.comments){
            NSMutableString *comments = [[NSMutableString alloc]init];
            NSMutableArray *attributedRangeArray = [NSMutableArray array];
            
            NSUInteger posStart = 0;
            for (int i = 0 ; i<data.comments.count; i++) {
                SNSPostCommentModel *comment = data.comments[i];
                
                
                
                NSMutableDictionary *rangeDict = [NSMutableDictionary dictionary];
                [rangeDict setObject:[NSValue valueWithRange:NSMakeRange(posStart, comment.senderName.length)] forKey:@"name"];
                [comments appendString:comment.senderName];
                posStart += (comment.senderName.length+1);
                
                NSString *createDateSinceNow = [UtilHelper intervalSinceNow:comment.createDate];
                [rangeDict setObject:[NSValue valueWithRange:NSMakeRange(posStart, createDateSinceNow.length)] forKey:@"createDate"];
                [comments appendFormat:@"\t%@\n",createDateSinceNow];
                posStart +=(createDateSinceNow.length+1);
                
                [comments appendString:comment.content];
                [rangeDict setObject:[NSValue valueWithRange:NSMakeRange(posStart, comment.content.length)] forKey:@"content"];
                posStart +=comment.content.length;
                
                
//                [comments appendFormat:@"%@:\t\t%@\n%@",comment.senderName, createDateSinceNow, comment.content];
                [attributedRangeArray addObject:rangeDict];
                
                if (i != data.comments.count-1) {
                    [comments appendString:@"\n"];
                    posStart ++;
                }
                
                
            }
            NSMutableAttributedString *commentAttributedString = [[NSMutableAttributedString alloc]initWithString:comments];
            NSLog(@"comment length is %d", comments.length);
            //UIColorFromRGB(0x027282, 1)
            for (NSDictionary *rangeDict in attributedRangeArray) {
                [commentAttributedString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x027282, 1) range:[rangeDict[@"name"] rangeValue]];
                [commentAttributedString addAttribute:(NSString *)kCTFontAttributeName value:CFBridgingRelease(CTFontCreateWithName((CFStringRef)[UIFont fontWithName:@"Helvetica Neue" size:12.0].fontName, 12, NULL)) range:[rangeDict[@"name"] rangeValue]];
                
                
                [commentAttributedString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xc4c4c4, 1) range:[rangeDict[@"createDate"] rangeValue]];
                [commentAttributedString addAttribute:(NSString *)kCTFontAttributeName value:CFBridgingRelease(CTFontCreateWithName((CFStringRef)[UIFont fontWithName:@"Helvetica Neue" size:10.0].fontName, 10, NULL)) range:[rangeDict[@"createDate"] rangeValue]];
                
                NSMutableParagraphStyle *alignParagraphStyle = [[NSMutableParagraphStyle alloc] init];
                alignParagraphStyle.lineSpacing = 5.0f;
//                alignParagraphStyle.alignment = NSTextAlignmentCenter;
                NSTextTab *t = [[NSTextTab alloc]initWithTextAlignment:NSTextAlignmentRight location:250 options:nil];
                alignParagraphStyle.tabStops = @[t];
                [commentAttributedString addAttribute:NSParagraphStyleAttributeName value:alignParagraphStyle range:[rangeDict[@"name"] rangeValue]];
                
                
                
                [commentAttributedString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x313131, 1) range:[rangeDict[@"content"] rangeValue]];
                [commentAttributedString addAttribute:(NSString *)kCTFontAttributeName value:CFBridgingRelease(CTFontCreateWithName((CFStringRef)[UIFont fontWithName:@"Helvetica Neue" size:12.0].fontName, 12, NULL)) range:[rangeDict[@"content"] rangeValue]];
                
                NSMutableParagraphStyle *spaceParagraphStyle = [[NSMutableParagraphStyle alloc] init];
//                spaceParagraphStyle.lineHeightMultiple = 25.0f;
//                spaceParagraphStyle.maximumLineHeight = 25.0f;
//                spaceParagraphStyle.minimumLineHeight = 25.0f;
//                spaceParagraphStyle.lineSpacing = 15.0f;
                spaceParagraphStyle.paragraphSpacing = 15.0f;
                [commentAttributedString addAttribute:NSParagraphStyleAttributeName value:spaceParagraphStyle range:[rangeDict[@"content"] rangeValue]];
            }
            
            /*
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineHeightMultiple = 15.0f;
            paragraphStyle.maximumLineHeight = 15.0f;
            paragraphStyle.minimumLineHeight = 15.0f;
            NSDictionary *ats = @{NSFontAttributeName : [UIFont fontWithName:@"Helvetica Neue" size:12.0], NSParagraphStyleAttributeName : paragraphStyle};
             */
            self.commentTextView.attributedText = commentAttributedString;
           
        }
        
        if (data.plusOneList) {
            [self setPlusOneImageViewList ];
        }
        
        
        for (UIView *subView in self.markContainerView.subviews) {
            [subView removeFromSuperview];
        }
        if (data.markList) {
            [self setMarkList];
        }
        
    }
}


-(void)openPhoto{
    if (_data.photo) {
        [self.viewController openPhoto:_data.photo];
    }
}


- (IBAction)plusOneAction:(id)sender {
    UIButton *button = sender;
    button.userInteractionEnabled = NO;
    NSString *uriString;
    if (_data.isPlusOne) {
        uriString= [NSString stringWithFormat:@"Messages/%@/unPlusOne.json", _data.id];
    }else{
        uriString= [NSString stringWithFormat:@"Messages/%@/plusOne.json", _data.id];
    }
    
    NSDictionary *parameters = @{@"key": self.viewController.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            _data.isPlusOne = !_data.isPlusOne;
            [self togglePlusOneButton:_data.isPlusOne];
            
            if (self.delegate) {
                [self.delegate didTouchedPlusOne];
            }
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
        button.userInteractionEnabled = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
        button.userInteractionEnabled = YES;
    }];
}
- (IBAction)beginCommentAction:(id)sender {
    [self.viewController performSegueWithIdentifier:@"toCommentView" sender:_data.id];
}
- (IBAction)favoriteButton:(id)sender {
    NSLog(@"favorite post id = %@", _data.id);
    UIButton *button = sender;
    button.userInteractionEnabled = NO;
    
    NSString *uriString;
    if ([_data.isFavorite isEqualToNumber:@(1)]) {
        uriString= [NSString stringWithFormat:@"Messages/%@/unFavorite.json", _data.id];
    }else{
        uriString= [NSString stringWithFormat:@"Messages/%@/favorite.json", _data.id];
    }
    
    NSDictionary *parameters = @{@"key": self.viewController.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            
            NSLog(@"favorite state is %@", _data.isFavorite);
            if ([_data.isFavorite isEqualToNumber: @(0)]) {
                _data.isFavorite = @(1);
            }else{
                _data.isFavorite = @(0);
            }
            
            if ([_data.isFavorite isEqualToNumber:@(1)]) {
                [self.favoriteButton setBackgroundImage: [UIImage imageNamed:@"iconStarBlue"]forState:UIControlStateNormal];
            }else{
                [self.favoriteButton setBackgroundImage: [UIImage imageNamed:@"iconStarGray"]forState:UIControlStateNormal];
            }
            button.userInteractionEnabled = YES;

        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
        button.userInteractionEnabled = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
        button.userInteractionEnabled = YES;
    }];
}

-(void)togglePlusOneButton:(BOOL)enable{
    if (!enable) {
        [self.plusOneButton setTitleColor:RGBACOLOR(195, 195, 195, 1) forState:UIControlStateNormal];
        
        [self.plusOneButton setImage:[UIImage imageNamed:@"icon未赞"] forState:UIControlStateNormal];
        
        [self.plusOneButton setTitle:@"赞" forState:UIControlStateNormal];
        
    }else{
        [self.plusOneButton setTitleColor:RGBACOLOR(92, 175, 238, 1) forState:UIControlStateNormal];
        [self.plusOneButton setImage:[UIImage imageNamed:@"icon已赞"] forState:UIControlStateNormal];
        [self.plusOneButton setTitle:@"已赞" forState:UIControlStateNormal];
    }
    

}

-(void)setPlusOneImageViewList {
    NSArray *plusOneList = _data.plusOneList;
    
    NSUInteger plusOneCount = plusOneList.count;
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    //set view and del other
    for (int i = 0; i < self.plusOneImageViewList.count; i++) {
        UIImageView *imageView = self.plusOneImageViewList[i];
        if (plusOneCount<= self.plusOneImageViewList.count) {
            //add & remove other
            if (i<plusOneCount) {
                SNSPlusOneModel *plusOne = plusOneList[i];
                if ([plusOne.photo.absoluteString isEqualToString:appDelegate.user[@"photo"]]) {
                    imageView.image = appDelegate.userPhoto;
                }else{
                    [imageView setImageWithURL:plusOne.photo placeholderImage:[UIImage imageNamed:@"image小助手-头像"]];
                }
                
                imageView.hidden = NO;
            }else{
                imageView.hidden = YES;
            }
        }else{
            //add and count other display number in last one
            
            if (i < self.plusOneImageViewList.count-1) {
                
                SNSPlusOneModel *plusOne = plusOneList[i];
                if ([plusOne.photo.absoluteString isEqualToString:appDelegate.user[@"photo"]]) {
                    imageView.image = appDelegate.userPhoto;
                }else{
                    [imageView setImageWithURL:plusOne.photo placeholderImage:[UIImage imageNamed:@"image小助手-头像"]];
                }
            }else{
                //last one
                
                NSString *numberString = [NSString stringWithFormat:@"%x", plusOneCount- self.plusOneImageViewList.count+1];
                
                CGSize imageSize = imageView.frame.size;
                UIImage *image = [[UIImage alloc]init];
                //                image.size = imageSize;
                UIFont *font = [UIFont boldSystemFontOfSize:20];
                UIGraphicsBeginImageContext(imageSize);
//                [image drawInRect:CGRectMake(0,0,imageSize.width,imageSize.height)];
//                [[UIColor lightTextColor] set];
                [numberString drawInRect:CGRectMake(9, 3, imageSize.width, imageSize.height) withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:[UIColor grayColor]}];
                image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                
                [imageView setImage:image];
                
            }
            
            imageView.hidden = NO;
        }
    }
    
    
}

-(void)setMarkList{
    
    for (SNSMarkModel *data  in self.data.markList) {
        SNSMarkLabelView *mark = [[SNSMarkLabelView alloc]initWithText:data.contentText pos:data.pos direction:data.markDirection];
        mark.userInteractionEnabled = NO;
        [self.markContainerView addSubview:mark];
        
    }
}



@end
